package com.zhxs.nfcscan.view;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.zhxs.nfcscan.R;
import com.zhxs.nfcscan.base.app.AppActivity;
import com.zhxs.nfcscan.base.dialog.TipsDialog;
import com.zhxs.nfcscan.utils.NFCTools;
import com.zhxs.nfcscan.utils.NFCUtil;
import com.zhxs.nfcscan.utils.NfcMessageParser;
import com.zhxs.utils.LogUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

public class CardTestActivity extends AppActivity {
    
    private Tag tag;
    
    // UI组件
    private EditText etCardNumber;
    private Button btnScanCard;
    private LinearLayout layoutCardDetails;
    private TextView tvCardId;
    private TextView tvCardContent;
    private TextView tvCardType;
    private TextView tvMaxSize;
    
    // 状态变量
    private boolean isScanning = false;
    private NfcAdapter nfcAdapter;
    private NFCUtil nfcUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.d("onResume()");
        Intent intent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.d("onPause()");
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_card_test;
    }
    
    @Override
    protected void initView() {
        // 初始化标题栏
        initTitleBar();
        
        // 初始化UI组件
        etCardNumber = findViewById(R.id.et_card_number);
        btnScanCard = findViewById(R.id.btn_scan_card);
        layoutCardDetails = findViewById(R.id.layout_card_details);
        tvCardId = findViewById(R.id.tv_card_id);
        tvCardContent = findViewById(R.id.tv_card_content);
        tvCardType = findViewById(R.id.tv_card_type);
        tvMaxSize = findViewById(R.id.tv_max_size);
        
        // 设置点击监听器
        btnScanCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onScanCardClick();
            }
        });
        
        // 初始隐藏详细信息
        layoutCardDetails.setVisibility(View.GONE);
    }
    
    @Override
    protected void initData() {
    }
    
    /**
     * 初始化标题栏
     */
    private void initTitleBar() {
        // 设置标题
        setTitle(getString(R.string.card_test));
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.d("onNewIntent()");
        processTag(intent);
    }
    
    /**
     * 处理NFC标签
     */
    private void processTag(Intent intent) {
        tag = NFCTools.Companion.getNFCTagFromIntent(intent);
        if (tag == null) {
            Toast.makeText(this, getString(R.string.nfc_read_failed), Toast.LENGTH_SHORT).show();
            return;
        }
        
        String[] str = tag.getTechList();
        String datas = "";
        
        // 获取标签id数组
        byte[] bytesId = tag.getId();
        
        NfcMessageParser nfcMessageParser = new NfcMessageParser(intent);
        List<String> tagMessage = nfcMessageParser.getTagMessage();
        
        if (tagMessage == null || tagMessage.size() == 0) {
            LogUtil.d(getString(R.string.nfc_format_not_supported));
        } else {
            for (int i = 0; i < tagMessage.size(); i++) {
                LogUtil.e("NFC Message: " + tagMessage.get(i));
            }
            datas = tagMessage.get(0);
        }
        
        // 显示NFC读取结果
        showNfcResult(datas, bytesId);
        
        // 重置扫描状态
        isScanning = false;
        updateScanButton();
    }
    
    /**
     * 显示NFC读取结果
     */
    private void showNfcResult(String content, byte[] cardId) {
        String cardIdHex = NfcMessageParser.bytesToHexString(cardId, false);
        
        // 显示卡片ID到输入框
        etCardNumber.setText(cardIdHex);
        
        // 显示详细信息
        layoutCardDetails.setVisibility(View.VISIBLE);
        
        // 设置卡片ID
        tvCardId.setText(getString(R.string.card_id) + ": " + cardIdHex);
        
        // 设置卡片内容
        if (content != null && !content.isEmpty()) {
            tvCardContent.setText(getString(R.string.card_content) + ": " + content);
            Toast.makeText(this, getString(R.string.nfc_read_success), Toast.LENGTH_SHORT).show();
        } else {
            tvCardContent.setText(getString(R.string.card_content) + ": " + getString(R.string.empty_content));
            LogUtil.d(getString(R.string.nfc_read_failed));
        }
        
        // 分析NFC卡的类型
        analyzeCardType();
        
        LogUtil.d("Card Test - ID: " + cardIdHex + ", Content: " + content);
    }
    
    /**
     * 分析NFC卡的类型
     */
    private void analyzeCardType() {
        if (tag == null) return;
        
        String[] techList = tag.getTechList();
        String cardType = "";
        String maxSize = "";
        
        for (String tech : techList) {
            if (TextUtils.equals(tech, "android.nfc.tech.Ndef")) {
                Ndef ndef = Ndef.get(tag);
                if (ndef != null) {
                    cardType = "NDEF";
                    maxSize = ndef.getMaxSize() + " 字节";
                }
            } else if (TextUtils.equals(tech, "android.nfc.tech.MifareClassic")) {
                cardType = "Mifare Classic";
            } else if (TextUtils.equals(tech, "android.nfc.tech.MifareUltralight")) {
                cardType = "Mifare Ultralight";
            }
        }
        
        if (TextUtils.isEmpty(cardType)) {
            cardType = getString(R.string.unknown_card_type);
        }
        
        tvCardType.setText(getString(R.string.card_type) + ": " + cardType);
        tvMaxSize.setText(getString(R.string.max_size) + ": " + maxSize);
    }
    
    /**
     * 刷卡按钮点击
     */
    private void onScanCardClick() {
        if (!isScanning) {
            // 开始扫描
            isScanning = true;
            updateScanButton();
            Toast.makeText(this, getString(R.string.please_scan_card), Toast.LENGTH_LONG).show();
            
            // 清空之前的信息
            etCardNumber.setText("");
            layoutCardDetails.setVisibility(View.GONE);
        } else {
            // 停止扫描
            isScanning = false;
            updateScanButton();
            Toast.makeText(this, getString(R.string.scan_cancelled), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 更新扫描按钮状态
     */
    private void updateScanButton() {
        if (isScanning) {
            btnScanCard.setText(getString(R.string.cancel_scan));
            btnScanCard.setBackgroundResource(R.drawable.button_secondary_background);
        } else {
            btnScanCard.setText(getString(R.string.scan_card));
            btnScanCard.setBackgroundResource(R.drawable.button_primary_background);
        }
    }
    
    /**
     * 读取nfc内容
     */
    protected final String readNfcContent() {
        String resultMsg = "";
        if (tag == null) return resultMsg;
        
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            try {
                ndef.connect();
                NdefMessage ndefMessage = ndef.getNdefMessage();
                if (ndefMessage != null) {
                    byte[] msg = ndefMessage.toByteArray();
                    byte[] realMsg = new byte[msg.length - 3];
                    for (int i = 3; i < msg.length; i++) {
                        realMsg[i - 3] = msg[i];
                    }
                    if (realMsg.length != 0) {
                        resultMsg = new String(realMsg, Charset.forName("UTF-8"));
                    } else {
                        resultMsg = "";
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.e("Read NFC content failed: " + e.getMessage());
            } finally {
                try {
                    ndef.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultMsg;
    }
}









